package com.itboye.mengwu.app.ui.aiwujia;

import java.io.Externalizable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import org.apache.commons.logging.LogConfigurationException;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager.OnActivityResultListener;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import u.aly.by;

import com.alipay.a.a.e;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.location.Poi;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.ImageCompress;
import com.itboye.core.utils.ImageCompressAndUpload;
import com.itboye.core.utils.ImageCompressAndUpload.OnUploadlistener;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.SoftwareUtil;
import com.itboye.core.utils.XImageLoader;
import com.itboye.mengwu.R;
import com.itboye.mengwu.address.AddressSelectView;
import com.itboye.mengwu.address.AddressSelectView2;
import com.itboye.mengwu.address.CityModel;
import com.itboye.mengwu.address.ProvinceModel;
import com.itboye.mengwu.app.MainApplication;
import com.itboye.mengwu.app.ui.mymeng.ActivityGeRenData;
import com.itboye.mengwu.data.model.LuntanTieZiBean;
import com.itboye.mengwu.data.presenter.NewMaMaZengPresenter;
import com.itboye.mengwu.data.presenter.TieZiPresenter;
import com.itboye.mengwu.testpic.ui.Bimp;
import com.itboye.mengwu.testpic.ui.FileUtils;
import com.itboye.mengwu.testpic.ui.PhotoActivity;
import com.itboye.mengwu.widget.FixGridLayout;
import com.itboye.mengwu.widget.MyGridView;
import com.itboye.mengwu.widget.PhotoSelectFragment;
import com.itboye.mengwu.widget.PhotoSelectFragment.PhotoSelectListener;

public class ActivityAiwujiaMomPublish extends BaseActivity implements
		Observer, OnClickListener {

	public final int EXTERNAL_ADDRESS_REQ_CODE = 10;
	public final int EXTERNAL_CAMERA_REQ_CODE = 11;
	public final int EXTERNAL_STORE_REQ_CODE = 12;
	private MyGridView aiWuJiaGridView;
	private GridAdapter adapter;
	// private TextView activity_selectimg_send;
	// private ImageView imgPublishBack;
	// 标题
	private EditText edttitle;
	// 内容
	private EditText edtcontext;
	private String title;
	private String contextEd;
	TextView txt_save;
	// TieZiPresenter tanPresenter;
	public final static int HU = 0;
	TextView place;
	AddressSelectView2 addressselect;
	String QUYU = "";
	private PopupWindow popupWindow;

	NewMaMaZengPresenter newMaMaZengPresenter;

	boolean ischeck = false;
	FixGridLayout biaoqian;
	ImageView back;
	TextView txt_title, fenleiTv;
	Button btn_ok;
	TextView baoyou, daofu;
	LocationManager locationManager = null;
	ImageView fenleiIv;
	public LocationClient mLocationClient = null;
	public BDLocationListener myListener = new MyLocationListener();
	String cate_name;
	String cate_id;
	String payType = "0";
	String addresss;
	// AddressSelectView asv =new AddressSelectView(this);
	String provinceNo, cityNo;

	RelativeLayout fenleiLine;

	PopupWindows popupWindows;

	// 数据库
	private SQLiteDatabase db;

	List<ProvinceModel> provinceLv = new ArrayList<ProvinceModel>();
	List<CityModel> cityLv = new ArrayList<CityModel>();
	private String DB_PATH;// =App.ctx.getCacheDir().getCanonicalPath() +
							// "/address";
	private final String DB_FILENAME = "itboye.db";

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_publish_mamazeng;
	}

	@Override
	public void onMyCreate() {
		// tanPresenter = new TieZiPresenter(this);
		File file1 = new File(Environment.getExternalStorageDirectory()
				+ "/myimage/");
		if (!file1.exists()) {
			file1.mkdirs();
		}
		Intent intent = getIntent();
		cate_name = intent.getStringExtra("cate_name");
		cate_id = intent.getStringExtra("cate_id");

		if (!"".equals(cate_name) || cate_name != null) {
			fenleiTv.setText(cate_name);
		}

		newMaMaZengPresenter = new NewMaMaZengPresenter(this);
		txt_title.setText("发布内容");
		place = (TextView) findViewById(R.id.place);
		Init();

		dingweiPermission();

		place.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dingweiPermission();
				showPopupQuYuWindow(v);
			}
		});

		mLocationClient = new LocationClient(getApplicationContext()); // 声明LocationClient类
		mLocationClient.registerLocationListener(myListener);
		initLocation();

		fenleiLine.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ActivityAiwujiaMomPublish.this,
						ActivityMaMaZengFaBuFenLei.class);
				startActivityForResult(intent, 101);
				// finish();
			}
		});
		baoyou.setOnClickListener(new OnClickListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				baoyou.setTextColor(getResources().getColor(R.color.main_color));
				baoyou.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn2));
				daofu.setTextColor(getResources().getColor(R.color.black_view));
				daofu.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn1));
				payType = "0";

			}
		});

		daofu.setOnClickListener(new OnClickListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				daofu.setTextColor(getResources().getColor(R.color.main_color));
				daofu.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn2));
				baoyou.setTextColor(getResources().getColor(R.color.black_view));
				baoyou.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn1));
				payType = "1";
			}
		});
	}

	private StringBuffer attachments;
	protected ArrayList<String> uploadedUrl = new ArrayList<String>();
	public static ArrayList<String> imgUrls = new ArrayList<>();

	public void Init() {
		aiWuJiaGridView = (MyGridView) findViewById(R.id.aiWuJiaGridView);
		aiWuJiaGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new GridAdapter(this);
		aiWuJiaGridView.setAdapter(adapter);
		aiWuJiaGridView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == imgUrls.size()) {
					popupWindows = new PopupWindows(
							ActivityAiwujiaMomPublish.this, aiWuJiaGridView);
					SoftwareUtil.showOrHideSoftware(arg1,
							MainApplication.context, false);
				} else {
					Intent intent = new Intent(ActivityAiwujiaMomPublish.this,
							PhotoActivity.class);
					intent.putExtra("imgUrls", imgUrls);
					intent.putExtra("ID", arg2);
					intent.putExtra("type", "aiwujia");
					startActivityForResult(intent, 101);
					// finish();

				}
			}
		});
	}

	public void onBitMap() {
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < imgUrls.size(); i++) {
			String Str = imgUrls.get(i).substring(
					imgUrls.get(i).lastIndexOf("/") + 1,
					imgUrls.get(i).lastIndexOf("."));
			list.add(FileUtils.SDPATH + Str + ".JPEG");
		}

		// 高清的压缩图片全部就在 list 路径里面了
		// 高清的压缩过的 bmp 对象 都在 Bimp.bmp里面
		// 完成上传服务器后 .........

		title = edttitle.getText().toString().trim();
		contextEd = edtcontext.getText().toString().trim();

		if (title == null || title == "") {
			ByAlert.alert("请输入标题");
			return;
		}
		if (contextEd == null || contextEd == "") {
			ByAlert.alert("请输入内容");
			return;
		}
		// final TieZiPresenter tanPresenter = new TieZiPresenter(this);
		newMaMaZengPresenter = new NewMaMaZengPresenter(this);
		if (imgUrls.size() > 0) {
			for (int j = 0; j < imgUrls.size(); j++) {
				System.out.println("路径" + imgUrls.get(j));
				ImageCompressAndUpload.getInstance().execute(imgUrls.get(j),
						new OnUploadlistener() {

							@Override
							public void OnSuccess(String resultData) {
								uploadedUrl.add(resultData);
								ByAlert.alert("图片成功");

								if (uploadedUrl.size() == imgUrls.size()) {
									if (uploadedUrl.size() > 0) {

										attachments = new StringBuffer();
										attachments.append(uploadedUrl.get(0));
										for (int i = 1; i < uploadedUrl.size(); i++) {
											attachments.append(",").append(
													uploadedUrl.get(i));
										}

									}
									LuntanTieZiBean bean = new LuntanTieZiBean();
									bean.setUid((String) SPUtils.get(
											ActivityAiwujiaMomPublish.this,
											null, SpPublicParams.UID, ""));
									bean.setSubject(title);
									bean.setMessage(contextEd);
									bean.setAuthor((String) SPUtils.get(
											ActivityAiwujiaMomPublish.this,
											null, SpPublicParams.NICK_NAME, ""));
									bean.setFid(5 + "");
									bean.setAttachments(attachments);
									// tanPresenter.add(bean);
									// TODO
									// newMaMaZengPresenter.fabu(
									// (String)
									// SPUtils.get(ActivityAiwujiaMomPublish.this,
									// null,
									// SpPublicParams.UID, ""),
									// title, contextEd, cate_id, payType,
									// ImageCompress.compress(attachments+"") +
									// "",
									// cityNo, "");
									newMaMaZengPresenter.fabu(
											(String) SPUtils
													.get(ActivityAiwujiaMomPublish.this,
															null,
															SpPublicParams.UID,
															""), title,
											contextEd, cate_id, payType,
											attachments + "" + "", cityNo, "");
								}

							}

							@Override
							public void OnError(String resultData) {
								ByAlert.alert("发表出错了╰(￣▽￣)╭");
								// toast.show();
							}
						}, "bbs");
			}
		} else {
			LuntanTieZiBean bean = new LuntanTieZiBean();
			bean.setUid((String) SPUtils.get(ActivityAiwujiaMomPublish.this,
					null, SpPublicParams.UID, ""));
			bean.setSubject(title);
			bean.setMessage(contextEd);
			bean.setAuthor((String) SPUtils.get(ActivityAiwujiaMomPublish.this,
					null, SpPublicParams.NICK_NAME, ""));
			bean.setFid(5 + "");
			bean.setAttachments(null);

			newMaMaZengPresenter.fabu((String) SPUtils.get(
					ActivityAiwujiaMomPublish.this, null, SpPublicParams.UID,
					""), title, contextEd, cate_id, payType, "", cityNo, "");
			// tanPresenter.add(bean);
			// TODO
			// newMaMaZengPresenter.fabu(uid, title, message, cate_id, template,
			// show_imgs, country, province, city,
			// address, main_img);
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@SuppressLint("HandlerLeak")
	public class GridAdapter extends BaseAdapter {
		private LayoutInflater inflater; // 视图容器
		private int selectedPosition = -1;// 选中的位置
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public int getCount() {
			return (imgUrls.size() + 1);
		}

		public Object getItem(int arg0) {

			return null;
		}

		public long getItemId(int arg0) {

			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		/**
		 * ListView Item设置
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			final int coord = position;
			ViewHolder holder = null;
			if (convertView == null) {

				convertView = inflater.inflate(R.layout.item_published_grida,
						parent, false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.item_grida_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (position == imgUrls.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
				if (position == 9) {
					holder.image.setVisibility(View.GONE);
				}
			} else {
				holder.image.setTag("file://" + imgUrls.get(position));
				XImageLoader.load("file://" + imgUrls.get(position),
						holder.image);
			}

			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
		}

	}

	public String getString(String s) {
		String path = null;
		if (s == null)
			return "";
		for (int i = s.length() - 1; i > 0; i++) {
			s.charAt(i);
		}
		return path;
	}

	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, View parent) {

			View view = View
					.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);

			Button bt1 = (Button) view
					.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					cameraPermission();
				}
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					// Intent intent = new
					// Intent(ActivityAiwujiaMomPublish.this,
					// AiWuJiaTestPicActivity.class);
					// intent.putExtra("hu", HU);
					// startActivityForResult(intent, 1100);
					// dismiss();
					// finish();

					storePermission();
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
	}

	class PhotoSelect implements PhotoSelectListener {

		@Override
		public void onPhotoSelectFinish(List<String> paths) {
			for (String string : paths) {
				imgUrls.add(string);
			}
			adapter = new GridAdapter(ActivityAiwujiaMomPublish.this);
			aiWuJiaGridView.setAdapter(adapter);
			// adapter.notifyDataSetChanged();
		}

	}

	private static final int TAKE_PICTURE = 0x000000;
	private String path = "";
	public String addr;

	public void photo() {

		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			Intent openCameraIntent = new Intent(
					MediaStore.ACTION_IMAGE_CAPTURE);
			File file1 = new File(Environment.getExternalStorageDirectory()
					+ "/myimage/");
			if (!file1.exists()) {
				file1.mkdirs();
			}
			Log.e("file1!!!!!!", file1.getPath());

			File file = new File(Environment.getExternalStorageDirectory()
					+ "/myimage/", String.valueOf(System.currentTimeMillis())
					+ ".jpg");
			path = file.getPath();
			Uri imageUri = Uri.fromFile(file);
			openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

			openCameraIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivityForResult(openCameraIntent, TAKE_PICTURE);
		} else {
			ByAlert.alert("请插入sd卡");
		}

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == TAKE_PICTURE && resultCode == Activity.RESULT_OK) {
			Log.e("....", "~~~~");

			if (path == null || "".equals(path)) {
				return;
			}
			String sdStatus = Environment.getExternalStorageState();
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
				Log.v("TestFile",
						"SD card is not avaiable/writeable right now.");
				ByAlert.alert("SD card is not avaiable/writeable right now.");
				return;
			}

			imgUrls.add(path);
			adapter = new GridAdapter(this);
			aiWuJiaGridView.setAdapter(adapter);
		}
		if (resultCode == 101 & requestCode == 101) {
			cate_id = data.getStringExtra("cate_id");
			cate_name = data.getStringExtra("cate_name");
			fenleiTv.setText(cate_name);
		}
		if (requestCode == 101 && resultCode == 102) {
			adapter = new GridAdapter(this);
			aiWuJiaGridView.setAdapter(adapter);
		}
		// switch (requestCode) {
		// case requestCode == TAKE_PICTURE
		// && resultCode == RESULT_OK:
		// Log.e("....", "~~~~");
		// if (path == null || "".equals(path)) {
		// return;
		// }
		//
		// imgUrls.add(path);
		// adapter = new GridAdapter(this);
		// aiWuJiaGridView.setAdapter(adapter);
		// break;
		//
		// default:
		// break;
		// }
		// if (resultCode == 101 & requestCode == 101) {
		// cate_id = data.getStringExtra("cate_id");
		// cate_name = data.getStringExtra("cate_name");
		// fenleiTv.setText(cate_name);
		// }

	}

	@Override
	public void update(Observable observable, Object data) {
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == NewMaMaZengPresenter.FabuSuccess) {
				// ByAlert.alert(entity.getData() + "");
				ByAlert.alert("发布成功");
				edtcontext.setText("");
				edttitle.setText("");
				finish();
			} else if (entity.getEventType() == NewMaMaZengPresenter.FabuFail) {
				ByAlert.alert(entity.getData() + "");
			}
		}
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back:
			imgUrls.clear();
			finish();
			break;
		case R.id.edttitle:
			edttitle.setFocusable(true);
			edttitle.setFocusableInTouchMode(true);
			edtcontext.setFocusable(true);
			edtcontext.setFocusableInTouchMode(true);
			break;
		case R.id.btn_ok:

			if ("".equals(fenleiTv.getText().toString().trim())) {
				ByAlert.alert("请选择分类！");
				break;
			}
			if ("".equals(edttitle.getText().toString().trim())) {
				ByAlert.alert("标题不能为空！");
				break;
			}
			if ("".equals(edtcontext.getText().toString().trim())) {
				ByAlert.alert("请描述一下宝贝！");
				break;
			}
			if (imgUrls.size() == 0) {
				ByAlert.alert("请加入图片！");
				break;
			}

			showProgressDialog("发布中，请稍后", true);
			onBitMap();
			break;

		default:
			break;
		}
	}

	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// Receive Location
			StringBuffer sb = new StringBuffer(256);

			// sb.append("time : ");
			// sb.append(location.getTime());
			// sb.append("\nerror code : ");
			// sb.append(location.getLocType());
			// sb.append("\nlatitude : ");
			// sb.append(location.getLatitude());
			// sb.append("\nlontitude : ");
			// sb.append(location.getLongitude());
			// sb.append("\nradius : ");

			sb.append(location.getRadius());
			if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				addr = location.getAddrStr();
				addresss = location.getCityCode();
				place.setText(location.getAddrStr());
				Log.d("hu",
						location.getAddrStr() + "getCountry()"
								+ location.getCountry());
				sb.append("\ndescribe : ");
				sb.append("gps定位成功");
				getproviceNum(location.getProvince(), location.getCity());
				// provinceNo=asv.getproviceNum(location.getProvince());

			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
				sb.append("\naddr : ");
				sb.append(location.getAddrStr()); // 运营商信息
				addr = location.getAddrStr();
				place.setText(location.getAddrStr());
				location.getCity();
				String getcity = "";
				if (location.getCity() != null) {
					getcity = location.getCity();
				}
				getproviceNum(location.getProvince(), getcity);
				sb.append("网络定位成功");
			} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
				sb.append("\ndescribe : ");
				sb.append("离线定位成功，离线定位结果也是有效的");
			} else if (location.getLocType() == BDLocation.TypeServerError) {
				sb.append("\ndescribe : ");
				sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
			} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
				sb.append("\ndescribe : ");
				sb.append("网络不同导致定位失败，请检查网络是否通畅");
			} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
				sb.append("\ndescribe : ");
				sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
			}
			sb.append("\nlocationdescribe : ");
			sb.append(location.getLocationDescribe());// 位置语义化信息
			Log.d("hu",
					location.getLocationDescribe() + "位置语义化信息"
							+ location.getCountry());
			List<Poi> list = location.getPoiList();// POI数据 if (list != null) {
			sb.append("\npoilist size = : ");
			Log.d("hu", sb.toString() + "sb");
		}
	}

	private void initLocation() {
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);
		option.setCoorType("bd09ll");// 可选，默认gcj02，设置返回的定位结果坐标系
		int span = 1000;
		option.setScanSpan(span);
		option.setIsNeedAddress(true);// 可选，设置是否需要地址信息，默认不需要
		option.setOpenGps(true);// 可选，默认false,设置是否使用gps
		option.setLocationNotify(true);
		option.setIsNeedLocationDescribe(true);
		option.setIsNeedLocationPoiList(true);
		option.setIgnoreKillProcess(false);
		option.SetIgnoreCacheException(false);
		option.setEnableSimulateGps(false);// 可选，默认false，设置是否需要过滤gps仿真结果，默认需要
		mLocationClient.setLocOption(option);
		mLocationClient.start();
	}

	public void getproviceNum(String province, String city) {

		try {
			DB_PATH = this.getCacheDir().getCanonicalPath() + "/address";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		db = openDataBase();

		Cursor cursorCity = db.rawQuery("select * from common_city", null);
		while (cursorCity.moveToNext()) {
			CityModel cityModel = new CityModel(cursorCity.getString(2),
					cursorCity.getInt(1), cursorCity.getInt(3));
			cityLv.add(cityModel);
		}

		for (int i = 0; i < cityLv.size(); i++) {

			if (city.equals(cityLv.get(i).getName())) {
				cityNo = cityLv.get(i).getNumber() + "";
			}
		}
		cursorCity.close();

		Cursor cursor = db.rawQuery("select * from common_province", null);
		while (cursor.moveToNext()) {
			ProvinceModel province1 = new ProvinceModel(cursor.getString(2),
					cursor.getInt(1));
			provinceLv.add(province1);
		}

		// mProvinceDatas = new String[provinceLv.size()];
		for (int i = 0; i < provinceLv.size(); i++) {

			if (province.equals(provinceLv.get(i).getName())) {
				provinceNo = provinceLv.get(i).getNumber() + "";
			}
		}
		cursor.close();

		db.close();

	}

	private SQLiteDatabase openDataBase() {
		try {
			String dbFileName = DB_PATH + "/" + DB_FILENAME;
			File dir = new File(DB_PATH);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			if (!new File(DB_PATH, DB_FILENAME).exists()) {
				new File(DB_PATH, DB_FILENAME).createNewFile();
				InputStream is = getResources().openRawResource(R.raw.itboye);
				FileOutputStream fos = new FileOutputStream(dbFileName);
				byte[] buffer = new byte[8192];
				int count = 0;
				while ((count = is.read(buffer)) > 0) {
					fos.write(buffer, 0, count);
				}
				fos.close();
				is.close();
			}
			db = SQLiteDatabase.openOrCreateDatabase(dbFileName, null);
			return db;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] arg1,
			int[] grantResults) {
		// TODO Auto-generated method stub
		super.onRequestPermissionsResult(requestCode, arg1, grantResults);

		switch (requestCode) {
		case EXTERNAL_ADDRESS_REQ_CODE: {
			// 如果请求被拒绝，那么通常grantResults数组为空
			if (grantResults.length > 0
					&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
				// 申请成功，进行相应操作
				mLocationClient = new LocationClient(getApplicationContext()); // 声明LocationClient类
				mLocationClient.registerLocationListener(myListener);
				initLocation();
			} else {
				// 申请失败，可以继续向用户解释。

			}
			return;

		}
		case EXTERNAL_CAMERA_REQ_CODE: {
			if (grantResults == null || "".equals(grantResults)) {
				return;
			} else {
				if (grantResults.length > 0
						&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
					// 申请成功，进行相应操作
					photo();
					popupWindows.dismiss();
				} else {
					// 申请失败，可以继续向用户解释。

				}
			}
			return;
		}
		case EXTERNAL_STORE_REQ_CODE: {

			if (grantResults.length > 0
					&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
				// 申请成功，进行相应

				PhotoSelectFragment photoSelectFragment = new PhotoSelectFragment(
						new PhotoSelect(), 9);
				photoSelectFragment.show(getSupportFragmentManager(), null);

			} else {
				// 申请失败，可以继续向用户解释。

			}
			return;
		}
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle arg0) {
		// TODO Auto-generated method stub
		// super.onSaveInstanceState(arg0);
	}

	public void dingweiPermission() {

		if (ContextCompat.checkSelfPermission(this,
				Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

			// 如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
			if (ActivityCompat.shouldShowRequestPermissionRationale(this,
					Manifest.permission.ACCESS_FINE_LOCATION)) {
				Toast.makeText(this, "请去设置给小萌添加个权限，否则无法定位。", Toast.LENGTH_SHORT)
						.show();
			} else {
				// 进行权限请求
				ActivityCompat
						.requestPermissions(
								this,
								new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
								EXTERNAL_ADDRESS_REQ_CODE);
			}
		} else {
			mLocationClient = new LocationClient(getApplicationContext()); // 声明LocationClient类
			mLocationClient.registerLocationListener(myListener);
			initLocation();
		}

	}

	public void cameraPermission() {
		if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

			// 如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
			if (ActivityCompat.shouldShowRequestPermissionRationale(this,
					Manifest.permission.CAMERA)) {
				Toast.makeText(this, "请去设置给小萌添加个权限，否则打不开相机。",
						Toast.LENGTH_SHORT).show();
			} else {
				// 进行权限请求
				ActivityCompat.requestPermissions(this, new String[] {
						Manifest.permission.CAMERA,
						Manifest.permission.WRITE_EXTERNAL_STORAGE,
						Manifest.permission.READ_EXTERNAL_STORAGE },
						EXTERNAL_CAMERA_REQ_CODE);
			}
		} else {
			photo();
			popupWindows.dismiss();
		}
	}

	public void storePermission() {
		if (ContextCompat.checkSelfPermission(this,
				Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

			// 如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
			if (ActivityCompat.shouldShowRequestPermissionRationale(this,
					Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
				Toast.makeText(this, "请去设置给小萌添加个权限，否则不能读取相册。",
						Toast.LENGTH_SHORT).show();
			} else {
				// 进行权限请求
				ActivityCompat.requestPermissions(this, new String[] {
						Manifest.permission.WRITE_EXTERNAL_STORAGE,
						Manifest.permission.READ_EXTERNAL_STORAGE },
						EXTERNAL_STORE_REQ_CODE);
			}
		} else {
			new PhotoSelectFragment(new PhotoSelect(), 9).show(
					getSupportFragmentManager(), null);
		}
	}

	private void showPopupQuYuWindow(View view) {

		View contentView = LayoutInflater.from(this).inflate(
				R.layout.fragment_quyu, null);
		addressselect = (AddressSelectView2) contentView
				.findViewById(R.id.addressselect);

		contentView.findViewById(R.id.btn_confirm).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
					
						if (TextUtils.isEmpty(addressselect.getCityName())) {
							cityNo = addressselect.getProvinceNo() + "";
						} else {
							cityNo = addressselect.getCityNo() + "";
						}
						//ByAlert.alert(QUYU);
						// newMaMaZengPresenter.libiaofenye(name, cate_id,
						// page_no,
						// page_size, order, zone, uid, to_uid);
						
						popupWindow.dismiss();
						place.setText(addressselect.getProvinceName()
								+ addressselect.getCityName());
					}
				});

		popupWindow = new PopupWindow(contentView, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);

		// 一个自定义的布局，作为显示的内容
		popupWindow.setTouchable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		popupWindow.showAtLocation(view, Gravity.BOTTOM,0, 0);

	

		// popupWindow.setBackgroundDrawable(new BitmapDrawable());

	}
}
